package com.autodatabase.database;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.autodatabase.xml.model.DatabaseFactoryXmlModel;
import com.autodatabase.xml.model.FactoryItemXmlModel;

public class DatabaseUtil {
	public static List<String> showDatabases(String key) {
		FactoryItemXmlModel fxm = getDatabaseFactoryXmlModel(key);
		DatabaseConnection dcon = DatabaseConnectionFactory.getConnection(fxm); 
		List<String> catalogs = new ArrayList<String>();

		try {
			Connection conn = dcon.getConnection();
			DatabaseMetaData dmd = conn.getMetaData();
			ResultSet rs = dmd.getCatalogs();
			
			while (rs.next()) {
				catalogs.add(rs.getString("TABLE_CAT"));
			}
		} 
		catch (ClassNotFoundException e) {
			e.printStackTrace();
		} 
		catch (SQLException e) {
			e.printStackTrace();
		}

		return catalogs;
	}
	
	public static List<String> showTables(String key, String catalog) {
		FactoryItemXmlModel fxm = getDatabaseFactoryXmlModel(key);
		DatabaseConnection dcon = DatabaseConnectionFactory.getConnection(fxm);
		List<String> tables = new ArrayList<String>();

		try {
			Connection conn = dcon.getConnection();
			DatabaseMetaData dmd = conn.getMetaData();
			
			ResultSet rs = dmd.getTables(catalog, null, null, null);
			
			while (rs.next()) {
				tables.add(rs.getString("TABLE_NAME"));
			}
		} 
		catch (ClassNotFoundException e) {
			e.printStackTrace();
		} 
		catch (SQLException e) {
			e.printStackTrace();
		}

		return tables;
	}
	
	private static FactoryItemXmlModel getDatabaseFactoryXmlModel(String key) {
		DatabaseFactoryXmlModel model = DatabaseFactoryXmlModel.getInstance();
		FactoryItemXmlModel fxm = model.getItems().get(key);
		
		return fxm;
	}
}
